package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.other.exception.BusinessException;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.LoginInfo;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.service.ILoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public LoginInfo systemLogin(Employee employee) {

        Employee emp = employeeMapper.selectOneByUserName(employee.getUsername());
        if (emp == null) {
            throw new BusinessException("用户名不存在!");
        }
        String pwd = MD5.create().setSalt(emp.getSalt().getBytes()).digestHex(employee.getPassword());

        if (!StringUtils.equalsIgnoreCase(pwd, emp.getPassword())) {
            throw new BusinessException("密码错误!");
        }
        String token = IdUtil.fastSimpleUUID();
        LoginInfo loginInfo = BeanUtil.copyProperties(emp, LoginInfo.class);
        redisService.setStringKeyAndValue(token, loginInfo, 30);
        return loginInfo;
    }

    @Override
    public LoginInfo userLogin(User user) {
        return null;
    }
}
